package com.starry.module.system.core.oauth2.authorization.third.client;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.starry.module.system.core.oauth2.authorization.third.AbstractThireClient;
import com.starry.module.system.core.oauth2.entity.Oauth2ThirdAccount;
import com.starry.module.system.core.oauth2.entity.Oauth2ThirdClient;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * 第三方登录-微信小程序
 *
 * @author xiaoke
 */
@Slf4j
public class ThireClientWxCharMini extends AbstractThireClient {


    public ThireClientWxCharMini(String code, Oauth2ThirdClient thirdClientConfig) {
        super(code, thirdClientConfig);
    }

    @Override
    public Oauth2ThirdAccount loadUser(String code, String state) throws Exception {
        HashMap<String, Object> formData = new HashMap<>();
        formData.put("appid", thirdClientConfig.getClientId());
        formData.put("secret", thirdClientConfig.getClientSecret());
        formData.put("js_code", code);
        formData.put("grant_type", "authorization_code");

        String userInfoResult = HttpRequest.post(thirdClientConfig.getUserInfoUri())
                .form(formData)
                .execute().body();
        JSON userInfoObj = JSONUtil.parse(userInfoResult);

        Oauth2ThirdAccount userInfo = new Oauth2ThirdAccount();
        userInfo.setOpenid((String) userInfoObj.getByPath("openid"));
        userInfo.setToken((String) userInfoObj.getByPath("session_key"));
        userInfo.setCode(code);
        userInfo.setState(state);
        userInfo.setType(thirdClientConfig.getCode());
        userInfo.setRawTokenInfo(userInfoResult);
        
        return userInfo;
    }

    @Override
    public Oauth2ThirdClient getThirdClientConfig() {
        return thirdClientConfig;
    }
}
